package com.bw.paper.mvp.model;

import com.bw.paper.mvp.base.model.BaseEntity;
import com.bw.paper.mvp.base.model.BaseModel;
import com.bw.paper.mvp.contract.UserDetailsContract;
import com.bw.paper.mvp.model.entity.ResponseUserEntity;
import com.bw.paper.mvp.model.entity.UpdateUserEntity;
import com.bw.paper.mvp.model.entity.UploadFileEntity;
import com.bw.paper.network.Api;
import com.bw.paper.network.ChangeFunction;
import com.bw.paper.network.HttpFactory;
import com.bw.paper.network.HttpType;

import java.io.File;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class UserDetailsModel extends BaseModel implements UserDetailsContract.IUserDetailsModel {

    @Inject
    public UserDetailsModel(){}

    @Override
    public Observable<BaseEntity> requestUser(Map<String, Object> map) {
        return HttpFactory.getInstance().factory(HttpType.TOKENSIGNTYPE).getRetrofit()
                .create(Api.class).requestUser(createBody(map)).map(new ChangeFunction<ResponseUserEntity>());
    }

    @Override
    public Observable<BaseEntity> updateUser(Map<String, Object> map) {
        return  HttpFactory.getInstance().factory(HttpType.TOKENSIGNTYPE).getRetrofit()
                .create(Api.class).requestUpdateUser(createBody(map)).map(new ChangeFunction<UpdateUserEntity>());
    }

    @Override
    public Observable<UploadFileEntity> uploadHead(Map<String, Object> map) {
        String str = (String) map.get("file");
        File file = new File(str);
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),file);
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.addFormDataPart("file",str.substring(str.lastIndexOf("/")+1),requestBody);
        return HttpFactory.getInstance().factory(HttpType.UPLOADTYPE).getRetrofit().create(Api.class)
                .requestUploadHead(builder.build().parts());
    }
}
